<script setup lang="ts">
import DataManage from './components/DataManage.vue'
import { queryList } from '@/api/modules/teams'
import FullCalendar from '@fullcalendar/vue3'
import { Setting } from '@element-plus/icons-vue'
import type { ComponentExposed } from 'vue-component-type-helpers'
import elementResizeDetectorMaker from 'element-resize-detector'
import { debounce } from 'lodash-es'
import './style.scss'
// const DataManage = componentLoadAsync(
//   () => import('./components/DataManage.vue')
// );
import { useCurrentElement } from '@vueuse/core'
import type { Calendar } from '@fullcalendar/core'
import { calendarOptions } from './'
import { formatTime, intervalDays } from '@/utils'
import type { TeamsInfo } from '@/types'

// ------------------use------------------
// #region
const el = useCurrentElement()
const { vLoading, withLoading } = useDefineLoading()
const [isManage, setIsManage] = useState<boolean>(false)
const [teamsData, setTeamsData] = useState<TeamsInfo[]>([])
const [fullcalendarApi, setFullcalendarApi]
  = useState<Calendar | null>(null)
const [dateTime, setDateTime] = useState(
  formatTime(Date.now(), 'YYYY-MM'),
)

// #endregion
// ------------------静态变量------------------
// #region
const resizeObserver = elementResizeDetectorMaker()
const customButtons = {
  // 自定义按钮
  prevYear: {
    text: '上一年',
    click: () => {
      fullcalendarApi.value?.prevYear?.()
      switchDate()
    },
  },
  prev: {
    text: '上一周期',
    click: () => {
      fullcalendarApi.value?.prev?.()
      switchDate()
    },
  },
  next: {
    text: '下一周期',
    click: () => {
      fullcalendarApi.value?.next?.()
      switchDate()
    },
  },
  nextYear: {
    text: '下一年',
    click: () => {
      fullcalendarApi.value?.nextYear?.()
      switchDate()
    },
  },
  today: {
    text: '今日',
    click: () => {
      fullcalendarApi.value?.today?.()
      switchDate()
    },
  },
  dayGridMonth: {
    text: '月',
    click: () => {
      fullcalendarApi.value?.changeView?.('dayGridMonth')
    },
  },
  dayGridWeek: {
    text: '周',
    click: () => {
      fullcalendarApi.value?.changeView?.('dayGridWeek')
    },
  },
  dayGridDay: {
    text: '日',
    click: () => {
      fullcalendarApi.value?.changeView?.('dayGridDay')
    },
  },
}
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
const fullCalendarRef
  = ref<ComponentExposed<typeof FullCalendar>>()
// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region
const computedCalendarOptions = computed(() => {
  const m = teamsData.value.map((item) => {
    const title = `${item.teamsName}: ${
      item.indicatorCode
    } ${formatTime(
      item.startTime,
      'MM月DD hh:00',
    )}--${formatTime(item.endTime, 'MM月DD hh:00')},${
      item.startTime
    },${item.endTime}`
    // const title = {
    //   name: item.teamsName,
    //   code: item.indicatorCode,
    //   start: item.startTime,
    //   end: item.endTime
    // };
    return {
      title,
      start: item.startTime,
      end: item.endTime,
    }
  })
  return {
    ...calendarOptions,
    events: m,
    customButtons,
  }
})
// #endregion
// ------------------生命周期------------------
// #region
onMounted(() => {
  getTeamsData()
})
onMounted(() => {
  bindEvent()
})
// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
async function switchDate() {
  await nextTick()
  // console.log(fullcalendarApi.value?.view.title);

  const viewDate
    = fullcalendarApi.value?.view.title.replace(
      /(\d+)年(\d+)月(.+)?/,
      '$1,$2',
    )
  if (!viewDate)
    return
  const [y, m] = viewDate.split(',')
  const n = `${y}-${m?.padStart(2, '0')}`
  if (dateTime.value === n)
    return
  setDateTime(n)
  getTeamsData()
}
function bindEvent() {
  const api = fullCalendarRef.value?.getApi()
  setFullcalendarApi(api!)
  // console.log(api);
  // api?.changeView()
  resizeObserver.listenTo(
    el.value,
    debounce(async () => {
      await nextTick()
      api?.render()
    }, 300),
  )
}

async function getTeamsData() {
  const { data: res } = await withLoading(queryList)({
    pageNumber: 1,
    pageSize: 999,
    month: dateTime.value,
  })
  setTeamsData(res.records)
}
async function back() {
  setIsManage(false)
  await getTeamsData()
}
// #endregion
</script>

<template>
  <div
    v-loading
    class="padding-sm overflow flex-direction align-center relative flex gap-xs container"
  >
    <FullCalendar
      ref="fullCalendarRef"
      :options="computedCalendarOptions"
      class="width-fill height-fill"
    >
      <template #eventContent="{ event, timeText }">
        <template
          v-if="
            !intervalDays(
              event.title.split(',')[1],
              event.title.split(',')[2],
            )
          "
        >
          <div class="fc-daygrid-event-dot" />
          <div class="fc-event-time">
            {{ timeText }}
          </div>
          <div
            class="fc-event-title"
            :title="event.title.split(',')[0]"
          >
            {{ event.title.split(',')[0] }}
          </div>
        </template>
        <template v-else>
          <div class="fc-event-main">
            <div class="fc-event-main-frame">
              <div class="fc-event-time">
                {{ timeText }}
              </div>
              <div class="fc-event-title-container">
                <div class="fc-event-title fc-sticky">
                  {{ event.title.split(',')[0] }}
                </div>
              </div>
            </div>
          </div>
        </template>
      </template>
    </FullCalendar>
    <div class="rounded-fill float-button absolute">
      <el-button
        :icon="Setting"
        type="primary"
        size="large"
        circle
        @click="setIsManage(true)"
      />
    </div>
    <FullscreenModal v-model="isManage">
      <DataManage>
        <template #header>
          <el-page-header title="班组管理" @back="back">
            <template #content>
              <span>数据管理</span>
            </template>
          </el-page-header>
        </template>
      </DataManage>
    </FullscreenModal>
  </div>
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
.container {
  --container-right-width: 300px;

  .float-button {
    z-index: 90;
    bottom: 40px;
    right: 40px;
    box-shadow: 0px 0px 2px var(--el-color-primary),
      0px 0px 5px var(--el-color-primary),
      0px 0px 10px rgba(0, 0, 0, 0.05);
  }

  .view-calendar {
    min-width: 50vw;
  }
  &-right {
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    width: var(--container-right-width);
    &-header {
      border-bottom: 1px solid var(--el-border-color-light);
      span:first-of-type {
        color: var(--el-text-color-primary);
      }
      span:last-of-type {
        color: var(--el-text-color-placeholder);
        transition: color 0.2s;
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
  }
  .b-panel {
    --panel-width: var(--container-right-width);
  }
}
.team-item {
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  background-color: var(--el-color-info-light-9);
  p {
    color: var(--el-text-color-secondary);
  }
}
.manage {
  position: absolute;
  inset: 0px;
  z-index: 99;
  background-color: var(--el-bg-color-overlay);
}
//-------------样式穿透-------------
</style>
